 /**
 * @author caif
 * @fileoverview data bag app
 */
$(function() {
    var dataBagId = parent.$(".databag-flag").attr("dataBagId");
    var returnBtn = parent.$(".databag_return a");
    parent.$("#search_form").hide();
    $(document).click(function(){
    	parent.$(".fancy-tooltip , #headerBar").hide(200);
    })
    if(returnBtn.length > 0){
        returnBtn[0].href= parent.$(".databag-flag").attr("data-back");
    }
    var thumbnail = {
        id   : "",
        name : "",
        representations : "",
        download : false,
        path : "",
        size : "",
        dataBagId : dataBagId
    };
    var template = "<div class='thumbnail-item' id={{id}} data-preview={{preview}}>" +
    	 "<a class='thumbnail' href='#'>" +
    	    "<img alt='' src='/databag/bag/{{dataBagId}}/path/{{path}}'>" +
    	 "</a>" +
    	 "<div class='thumbnailName'>" +
        	    "<a >{{name}}</a>" +
        	 "</div>" +
        "</div>";
    var showRep = function(rep)
    {
    	for( var i=0 ; i < rep.length ; i++ )
        {
            //for rvt file
            if( rep[i].MIME == "image/png" && rep[i].Attributes.Category == "Preview" )
            {
                $("#databag-img").html( "<img src=/databag/bag/"+ dataBagId +"/path/"+rep[i].Path+" alt='正在加载 请稍候...'>" ).parent().show();
                $(".preview-btn").show()
                .unbind("click")
                .bind( "click" , {path : rep[i].Path , dataBagId : dataBagId} , function(e){
                    $("#databag-img").html( "<img src=/databag/bag/"+ e.data.dataBagId +"/path/"+ e.data.path+" alt='正在加载 请稍候...'>" ).parent().show();
                    $("#3D-Viewer-wrap , #flash-wrap , #thumbnails").hide();
                    $("#databag-img").show();
                });
                $("#3D-Viewer-wrap, #thumbnails, #flash-wrap ").hide();
                $("#databag-img").show();
            }
            else if( rep[i].MIME == "application/gmsb" )
            {
                $("#threed-btn").show().unbind("click").bind("click", {extension : "gmsb" , path : rep[i].Path ,dataBagId : dataBagId }, function(e){
                    TViewer.getData(e.data.path , e.data.extension ,e.data.dataBagId);
                });
            }
            else if( rep[i].MIME == "application/x-shockwave-flash" )
            {
                $("#nav_node .flash-btn").show().unbind("click").bind( "click" , {path : rep[i].Path , dataBagId : dataBagId} , function(e){
                $('#flash-wrap').FlexPaperViewer(
                { 
                        config : {
                        SWFFile : "/databag/bag/"+ e.data.dataBagId +"/path/"+e.data.path,
                        Scale : 0.6,
                        ZoomTransition : 'easeOut',
                        ZoomTime : 0.5,
                        ZoomInterval : 0.2,
                        FitPageOnLoad : true,
                        FitWidthOnLoad : false,
                        FullScreenAsMaxWindow : false,
                        ProgressiveLoading : false,
                        MinZoomSize : 0.2,
                        MaxZoomSize : 5,
                        SearchMatchAll : false,
                        InitViewMode : 'Portrait',
                        RenderingOrder : 'flash,html',
                        StartAtPage : '',

                        ViewModeToolsVisible : true,
                        ZoomToolsVisible : true,
                        NavToolsVisible : true,
                        CursorToolsVisible : true,
                        SearchToolsVisible : true,
                        WMode : 'window',
                        localeChain: 'en_US',
                        jsDirectory : "/databag/js/",
                        cssDirectory : "/databag/css/"
                    }
                 });
    	                $('#flash-wrap').show();
                        $("#3D-Viewer-wrap,#databag-img,#thumbnails").hide();
                    });
                }
            
            if( rep[i].Downloadable )
            {
            	var html = "";
            	if( rep[i].Description )
                {
            		html += "<li><a href=/databag/bag/"+dataBagId+"/path/"+rep[i].Path+"?download=true>"+rep[i].Description+"</a></li>";
                }
                else
                {
                	var defaultView = Databag.Metadata.DefaultView;
                    html += "<li><a href=/databag/bag/"+dataBagId+"/path/"+rep[i].Path+"?download=true>"+rep[i].MIME+"</a></li>";
                }
            }
        }
        if( html )
        {
            var iframe = $('<iframe style="position:absolute;top:30px;left:0;width:221px;height:66px;background-color:transparent;border:none;"></iframe>');
            $(".download-drop .dropdown-menu").html(html)
            .after(iframe.hide())
            .parent().show();
            $(".download-drop .dropdown-menu  li").click(function(){
                $(this).parents( ".download-drop" ).removeClass("open");
            });
            $('#dl-dropdown-toggle').click(function(){
            	iframe.show();
            	$(document).one('mousedown', function(){
        			iframe.hide();
            	});
            });
        };
        $("#nav_tab").delegate("li" , "click" , function(){
        	$("#nav_tab li").removeClass("active");
        	$(this).addClass("active");
        	$(".tab #nav_node li").removeClass("img-active");
        	$("#preview-btn").addClass("img-active");
        })
        $(".treeNode #nav_node").delegate("li:not(.dropdown)" , "click" , function(){
        	$(".treeNode #nav_node li").removeClass("active img-active");
        	$(this).addClass("active");
        })
        $(".tab #nav_node").delegate("li:not(.dropdown)" , "click", function(){
        	$(".tab #nav_node li").removeClass("active img-active");
        	$(this).addClass("img-active");
        })
    };
    $("#mask").show();
    $("#brand").text(decodeURIComponent(parent.$(".databag-flag").attr("filename"))).attr("title" ,decodeURIComponent(parent.$(".databag-flag").attr("filename")) );
    $.ajax({
        url: "/databag/bag/"+dataBagId+"/path/manifest.json",
        dataType: "json",
        success: function(data) {
            Databag.parseManifest(data);
            for ( var i = 0, length = Databag.Views.length ; i < length ; i++ )
            {
                if(Databag.Views[i].ID == Databag.Metadata.DefaultView)
                {
                    for( var j=0 ; j< Databag.Views[i].Representations.length ; j++ )
                    {
                        if( Databag.Views[i].Representations[j].Attributes.Category == "Preview" )
                        {
                            $("#databag-preview").html( "<img src=/databag/bag/"+ dataBagId +"/path/"+Databag.Views[i].Representations[j].Path+" alt='姝ｅ湪鍔犺浇 璇风◢鍊�..'>" ).show();
                            $("#3D-Viewer-wrap").hide();
                            break;
                        }
                    }
                    break;
                }
            }
//            parent.App.util.hideTip();
            $("#mask").hide();
            $("#databag-left").jstree({
                "json_data": Databag.jsonData,
                "plugins": ["themes", "json_data", "ui" , "types" ],
    	        "ui" : {
                    "initially_select" : [ "initial_node" ],
                    "select_limit" : 1
                },
                 "types" : {
                	 "valid_children" : [ "folder" ],
                    "types" : {
                        "viewer" : {
                            "icon" : {
                                "image" : "/databag/js/libs/jstree/themes/apple/drive.png"
                            }
                        }
                    }
                },
                "themes" : {
		            "theme" : "apple",
		            "url"   : "/databag/js/libs/jstree/themes/apple/style.css",
		            "dots" : false,
		            "icons" : true
		        },

            })
            .bind("select_node.jstree", function(e, data) {
                var rep = data.rslt.obj.data("Representations");
                parent.$("#fnav li").hide();
                parent.$(".databag_return").show();
                $(".modi ,.download-drop").hide();
                if( data.rslt.obj.data("root") )
                {
                    $("#thumbnails").empty().show();
                    $("#3D-Viewer-wrap,#databag-img-content").hide();
                    var views = data.rslt.obj.data("children"),
                    tabTpl = "<li tabid={{ID}}><a href='#'>{{Name}}</a></li><li class='divider-vertical'></li>",
                    type=data.rslt.obj.data("type");
                    $("#nav_tab").empty();
                    for( var i=0 ; i < views.length ; i++ )
                    {
                        thumbnail.name = views[i].data.Name;
                        thumbnail.id = views[i].data.ID;
                        if( type == "Tab")
                    	{
                    		$("#nav_tab").append( Mustache.to_html(tabTpl, views[i].data ) );
                    		$("#databag-right").attr("class" , "tab");
                    		$("#nav_tab li").click(function(){
                    			var rep = Databag.getRepByViewId($(this).attr("tabid"));
                        		showRep(rep);
                    		});
                    	}
                        else
                        {
                        	$("#databag-right").attr("class" , "treeNode");
                        }
                        for ( var j=0 ; j < views[i].metadata.Representations.length ; j++)
                        {
                            var category = views[i].metadata.Representations[j].Attributes.Category,
                                path = views[i].metadata.Representations[j].Path,
                                width = views[i].metadata.Representations[j].Attributes.Width,
                                height = views[i].metadata.Representations[j].Attributes.Height,
                                downloadable=views[i].metadata.Representations[j].Downloadable,
                                size = views[i].metadata.Representations[j].Size;
                            if( category == "Preview" )
                            {
                                thumbnail.preview = path;
                                continue;
                            }
                            
                            if( category == "Thumbnail"
                                && (( height == "96" && height >= width)|| (width == "96" &&  width >= height)))
                            {
                                thumbnail.download = downloadable;
                                thumbnail.path = path;
                                thumbnail.size = size;
                                $("#thumbnails").append( Mustache.to_html(template, thumbnail ) );
                                continue;
                            }
                        }
                    }
                    $(".thumbnail-item").click(function(){
                        var that = this;
                        var parentNode = $(".jstree-clicked");
                        var rep = Databag.getRepByViewId($(this).attr("id"));
                		showRep(rep);
                		if( type=="Tab" )
                		{
                			var self = this;
                			$("#nav_tab li").removeClass("active");
                			$("#preview-btn").addClass("img-active");
                			$("#nav_tab li").each( function(index , data){
                				if( $(data).attr("tabid") == $(self).attr("id"))
                				{
                					$(this).addClass("active");
                					$("#preview-btn").addClass("");
                					return false;
                				}
                			})
                		}
                    });
                }
                else{
                	$("#nav_tab").empty();
                	$("#databag-right").attr("class" , "treeNode");
                	$("#nav_node li").removeClass("active img-active");
                	$("#preview-btn").addClass("active");
                    if( rep )
                    {
                        var html = "";
                        $("#databag-img-header li[class$=btn]").hide();
                        $(".divider-vertical").show();
                        showRep(rep);
                    }
                }
            });
        }
    });
})
